package com.cd.music.controller;

import com.cd.music.annotation.Auth;
import com.cd.music.annotation.Parameter;
import com.cd.music.annotation.RequestLimit;
import com.cd.music.dto.FCodeDto;
import com.cd.music.dto.ResultBean;
import com.cd.music.model.FCode;
import com.cd.music.service.FCodeService;
import com.cd.music.utils.ExcelUtil;
import com.cd.music.utils.ResultUtil;
import com.cd.music.utils.StringUtil;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

/**
 * @author yxl 余秀良
 * @version 1.0
 * @description: F码控制器
 * @date 2018年03月02日  下午4:38
 * @address: 四川成都
 */
@Controller
@CrossOrigin
@RequestMapping("fCode")
@Auth(roles = "admin", sign = {0, 1}, description = "只有管理员和超级管理员可以访问")
public class FCodeController {
    @Resource(name = "fCodeService")
    private FCodeService fCodeService;

    /**
     * @author yxl 余秀良
     * @version 1.0
     * @description: 根据条数生成Ｆ码
     * @date 2018年03月13日 下午10:12
     * @address: 四川成都
     */
    @ResponseBody
    @RequestLimit(count = 5)
    @PostMapping("admin/create")
    public String createFCode(@Parameter FCodeDto dto) {
        return ResultUtil.result(fCodeService.batchCreate(dto.getTotal()));
    }

    @RequestLimit(count = 2)
    @RequestMapping("admin/exportExcel")
    public void exportExcel(@Param("pageIndex") String pageIndex, @Param("pageSize") String pageSize, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        FCodeDto dto = null;
        if (!StringUtil.isEmpty(pageIndex) && !StringUtil.isEmpty(pageSize)) {
            dto = FCodeDto.builder().pageIndex(Integer.valueOf(pageIndex)).pageSize(Integer.valueOf(pageSize)).build();
        }
        ResultBean resultBean = fCodeService.selectList(dto);
        if (resultBean.getIsSuccess()) {
            String path = request.getSession().getServletContext().getRealPath("/");
            resultBean = exportExcel(resultBean.getData(), path);
            if (resultBean.getIsSuccess()) {
                File file = (File) resultBean.getData();
                InputStream inputStream = new FileInputStream(file);
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1") + "");
                response.addHeader("Content-Length", "" + inputStream.available());
                response.setContentType("application/octet-stream;charset=UTF-8");
                OutputStream os = response.getOutputStream();
                byte[] b = new byte[1024];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                os.close();
                inputStream.close();
                file.delete();
            }
        }
    }

    /**
     * 导出excel表格
     *
     * @param fCodeList 数据集合
     * @return 返回成功还是失败
     */
    private ResultBean exportExcel(List<FCode> fCodeList, String path) {
        List<List<Object>> dataList = new LinkedList<>();
        //根据条数循环生成Ｆ码
        for (FCode code : fCodeList) {
            List<Object> list = new LinkedList<>();
            list.add(code.getValue());
            dataList.add(list);
        }
        ResultBean.Builder builder = ResultBean.builder();
        String nowTime = (LocalDateTime.now()).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        if (StringUtil.isEmpty(path)) {
            throw new RuntimeException("文件路径错误");
        }
        path = path + File.separator + "file";
        File file = new File(path);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new RuntimeException("文件夹创建失败");
            }
        }
        LinkedList<String> columnNameList = new LinkedList<>();
        columnNameList.add("F码");
        ExcelUtil build = ExcelUtil.newBuilder().setFilePath(path + File.separator + nowTime + ".xls").setSheetName(nowTime).setTitle("F码生成数据表").
                setColumnNameList(columnNameList).setDataList(dataList).setAppend(true).build();
        builder.data(build.writeExcel()).code(200).success(true);
        return builder.build();
    }

    @ResponseBody
    @RequestMapping("admin/fCode/list")
    public String fCodeList(@Parameter FCodeDto dto) {
        return ResultUtil.result(fCodeService.selectList(dto));
    }
}
